<template>
  <div class="container">
    <el-button type="warning" size="large" style="margin: 20px" @click="add"
      >添加热门景区</el-button
    >
    <el-table :data="somedata" style="width: 100%" border>
      <el-table-column prop="location" label="景区地点" width="100">
      </el-table-column>
      <el-table-column prop="city" label="景区城市" width="100">
      </el-table-column>
      <el-table-column prop="title" label="景区标题" width="180">
      </el-table-column>
      <el-table-column prop="imglist" label="景区图片" width="170">
        <template slot-scope="scope">
          <img
            :src="scope.row.imglist[0]"
            alt="图片"
            width="150"
            height="150"
          />
        </template>
      </el-table-column>
      <el-table-column prop="content" label="景区介绍">
        <template slot-scope="scope">
          <div
            v-html="scope.row.content"
            style="height: 100px; overflow: hidden"
          ></div>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180px">
        <template slot-scope="{ row }">
          <el-button
            type="success"
            icon="el-icon-zoom-in"
            size="mini"
            title="浏览"
            @click="watchdetail(row)"
          ></el-button>
          <el-button
            type="warning"
            icon="el-icon-edit"
            size="mini"
            title="编辑"
            @click="updateList(row)"
          ></el-button>

          <el-button
            slot="reference"
            type="danger"
            icon="el-icon-delete"
            size="mini"
            title="删除"
            @click="deleteList(row)"
            style="margin-left: 10px"
          ></el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页器 -->
    <el-pagination
      background
      style="margin-top: 20px; text-align: center"
      :current-page="page"
      :total="total"
      :page-size="limit"
      :pager-count="7"
      :page-sizes="[3, 5, 10]"
      layout="prev, pager, next, jumper,->,sizes,total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    >
    </el-pagination>
    <el-dialog
      title="景区详情"
      :visible.sync="dialogTableVisible"
      width="800px"
    >
      <div class="inbox">
        <div style="text-align: center; font-size: 20px; font-weight: 800">
          {{ nowitem.location }}
        </div>
        <div class="newcontent" v-html="nowitem.content"></div>
        <el-carousel
          :interval="4000"
          type="card"
          height="200px"
          style="margin-left: 100px; margin-top: 80px"
        >
          <el-carousel-item v-for="item in nowitem.imglist" :key="item">
            <img :src="item" style="width: 200px; height: 200px" />
          </el-carousel-item>
        </el-carousel>
        <el-divider>End.</el-divider>
      </div>
    </el-dialog>
    <el-dialog
      :title="title"
      :visible.sync="drawer"
      :before-close="handleClose"
      style="height: 100vh"
      width="1000px"
    >
      <div class="modify">
        <el-form ref="form" :model="form" label-width="80px">
          <el-form-item label="景区地点">
            <el-input v-model="form.location" style="width: 300px"></el-input>
          </el-form-item>
          <el-form-item label="景区城市">
            <el-input v-model="form.city" style="width: 300px"></el-input>
          </el-form-item>
          <el-form-item label="景区定位">
            <div style="display: flex; align-items: center">
              <el-button type="primary" @click="open">位置选择</el-button>
              <div
                v-if="thisPosition.address"
                style="font-weight: 800; margin-left: 20px"
              >
                {{ thisPosition.address }}
              </div>
            </div>
          </el-form-item>
          <el-form-item label="景区标题">
            <el-input
              type="textarea"
              v-model="form.title"
              maxlength="30"
              show-word-limit
              :autosize="{ minRows: 2, maxRows: 4 }"
              style="width: 500px"
            ></el-input>
          </el-form-item>
          <el-form-item label="景区照片" style="width: 100%; height: 100%">
            <span
              v-for="(item, index) in form.imglist"
              :key="index"
              style="margin-left: 20px"
              @click="deleteimg(index)"
            >
              <img :src="item" style="width: 200px; height: 200px" />
            </span>
            <el-upload
              class="avatar-uploader"
              action="http://127.0.0.1:2024/upload"
              :on-success="handleAvatarSuccess"
              :show-file-list="false"
            >
              <i
                class="el-icon-plus avatar-uploader-icon"
                style="width: 200px; height: 200px"
              ></i>
            </el-upload>
          </el-form-item>
          <el-form-item label="景区介绍">
            <fullcontent v-model="form.content"></fullcontent>
          </el-form-item>
        </el-form>

        <div class="demo-drawer__footer">
          <el-button @click="cancelForm">取 消</el-button>
          <el-button @click="finish">确 定</el-button>
        </div>
      </div>
    </el-dialog>
    <el-dialog
      title="景点位置选择"
      :visible.sync="mapdialogVisible"
      width="width"
      :before-close="mapdialogBeforeClose"
    >
      <div id="map-box">
        <div id="mymap"></div>
        <!-- 增加的部分 -->
        <div id="myPageTop">
          <input
            placeholder="请输入地址"
            id="tipinput"
            @keyup.enter.native="searchKeyWord"
            v-model="keyword"
          />

          <el-button icon="el-icon-search" @click="searchKeyWord" />
          <div class="map_search_result" v-if="showSearchResult">
            <div
              @click="markerResult(item)"
              class="item"
              v-for="(item, index) in poiList"
              :key="index"
            >
              {{ item.name }}
            </div>
          </div>
          <div id="panel"></div>
        </div>
      </div>

      <div slot="footer">
        <el-button @click="cancelplace">取 消</el-button>
        <el-button type="primary" @click="finishplace">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script type="text/javascript" src="https://webapi.amap.com/maps?v=2.0&key=c7317e56d00520642ad9b6c86e9e6b48"></script>
<script>
import {
  gethotdata,
  deletehotdata,
  updatehotdata,
  addehotdata,
} from "@/api/hot.js";

import fullcontent from "@/components/fullcontent";
import AMapLoader from "@amap/amap-jsapi-loader";

components: {
  fullcontent;
}

export default {
  name: "Login",
  components: {
    fullcontent,
  },
  aMap: null,
  data() {
    return {
      hotadata: [],
      page: 1, //分页器当前第几页
      limit: 5, //每一页需要展示几条数据
      total: 0,
      somedata: [],
      nowitem: {},
      dialogTableVisible: false,
      drawer: false,
      form: {},
      dialogImageUrl: "",
      dialogVisible: false,
      flag: 0, //0更新 1添加
      title: "景区信息更新",
      mapdialogVisible: false,
      map: null,
      aMap: null,
      keyword: "",
      auto: null, // 自动完成实例
      placeSearch: null, // 地点查询实例,
      geocoder: null,
      thisPosition: {},
      showSearchResult: false,
      poiList: [],
    };
  },
  mounted() {
    this.initdata();
  },
  methods: {
    initMap() {
      let that = this;
      console.log("执行了地图初始化");
      AMapLoader.reset();
      AMapLoader.load({
        key: "c7317e56d00520642ad9b6c86e9e6b48", // 申请好的Web端开发者Key，首次调用 load 时必填
        version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        plugins: [
          "AMap.ToolBar",
          "AMap.Scale",
          "AMap.Geolocation",
          "AMap.PlaceSearch",
          "AMap.AutoComplete",
          "AMap.Geocoder",
          "AMap.CitySearch",
        ],
        resizeEnable: true,
      })
        .then((AMap) => {
          const that = this;
          that.aMap = AMap;
          //输入提示
          var autoOptions = {
            input: "tipinput",
          };
          that.map = new AMap.Map("mymap", {
            //设置地图容器id
            resizeEnable: true,
            zoom: 12, //初始化地图级别
            center: [116.397428, 39.90923], // 初始化地图中心点位置
          });

          if (that.thisPosition.lng) {
            
            let marker = new AMap.Marker({
              position: new AMap.LngLat(
                that.thisPosition.lng,
                that.thisPosition.lat
              ),
            });
            this.map.clearMap(); // 清除所有覆盖物（点标志）
            this.map.add(marker); // 添加点标志
          }

          that.handleClick(AMap); //地图选点
          that.map.addControl(new AMap.Scale()); // 在图面添加比例尺控件，展示地图在当前层级和纬度下的比例尺
          that.map.addControl(new AMap.ToolBar()); //在图面添加鹰眼控件，在地图右下角显示地图的缩略图
          that.geocoder = new AMap.Geocoder();
          that.mapSearchInit();
        })
        .catch((e) => {
          console.log(e);
        });
    },

    //点击地图获取地理位置
    handleClick() {
      this.map.on("click", (e) => {
        let lng = e.lnglat.lng;
        let lat = e.lnglat.lat;
        let marker = new AMap.Marker({
          position: new AMap.LngLat(lng, lat),
        });
        this.map.clearMap(); // 清除所有覆盖物（点标志）
        this.map.add(marker); // 添加点标志
        let lnglat = [lng, lat];
        let that = this;
        that.geocoder.getAddress(lnglat, function (status, result) {
          if (status === "complete" && result.regeocode) {
            that.address = result.regeocode.formattedAddress;
            that.thisPosition = {
              address: that.address,
              lng: lng,
              lat: lat,
            };
            console.log(that.thisPosition);
          } else {
          }
        });
      });
    },
    /** 初始化搜索 */
    mapSearchInit() {
      let autoOptions = {
        input: "tipInput",
      };
      let autoCompleteComponent = new AMap.Autocomplete(autoOptions);
      this.autoCompleteComponent = autoCompleteComponent;
      // 注册placeSearch组件
      this.placeSearchComponent = new AMap.PlaceSearch();
    },
    //根据输入内容查询
    searchKeyWord() {
      let that = this;
      that.placeSearchComponent.search(that.keyword, function (status, result) {
        if (status === "complete" && result.info === "OK") {
          console.log(result);

          that.showSearchResult = true;
          that.poiList = result.poiList.pois;
          console.log(that.showSearchResult);
        } else {
          that.showsearchResult = false;
          that.poiList = [];
          that.$message({
            message: "没有查到结果",
            type: "warning",
          });
        }
      });
    },
    //选择搜索的内容
    markerResult(data) {
      this.showSearchResult = false;
      this.address = data.name;
      var marker = new AMap.Marker({
        position: [Number(data.location.lng), Number(data.location.lat)],
      });
      this.map.clearMap(); // 清除所有覆盖物（点标志）
      this.map.add(marker); // 添加点标志
      setTimeout(() => {
        this.map.setCenter(data.location);
        this.map.setZoom(15);
      }, 50);
      this.thisPosition = {
        address: this.address,
        lng: data.location.lng,
        lat: data.location.lat,
      };
      this.$emit("select", this.thisPosition);
    },
    cancelplace() {
      this.mapdialogVisible = false;
      this.keyword = "";
      this.thisPosition = {};
      this.poiList = [];
    },
    finishplace() {
      this.mapdialogVisible = false;
      this.keyword=''
      this.poiList = [];
    },
    async initdata() {
      let result = await gethotdata();
      // 假设 arr 是你要遍历的数组
      for (let i = 0; i < result.data.length; i++) {
        // 在循环中对数组中的元素进行操作
        result.data[i].imglist = JSON.parse(result.data[i].imglist); // 这里的 modifyElement 是你对元素进行修改的函数
      }
      if (result.status == 0) {
        this.hotadata = result.data;
        this.total = this.hotadata.length;
        this.somedata = this.hotadata.slice(
          (this.page - 1) * this.limit,
          (this.page - 1) * this.limit + this.limit
        );
        this.$store.dispatch("hot/savedata", this.hotadata);
      }
    },
    open() {
      this.mapdialogVisible = true;
      this.initMap();
    },
    handleCurrentChange(page) {
      this.page = page;
      this.somedata = this.hotadata.slice(
        (this.page - 1) * this.limit,
        (this.page - 1) * this.limit + this.limit
      );
    },
    handleSizeChange(limit) {
      this.page = 1;
      this.limit = limit;
      this.somedata = this.hotadata.slice(
        (this.page - 1) * this.limit,
        (this.page - 1) * this.limit + this.limit
      );
    },
    watchdetail(row) {
      this.nowitem = row;
      this.dialogTableVisible = true;
    },
    async deleteList(row) {
      this.$confirm("是否删除该景点, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          let result = await deletehotdata(row.id);
          if (result.status == 0) {
            this.$message({
              type: "success",
              message: "删除成功!",
            });
            this.initdata();
          } else {
            this.$message.error(result.message);
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    async updateList(row) {
      this.form = JSON.parse(JSON.stringify(row));
      this.form.position = JSON.parse(this.form.position);
      this.thisPosition = this.form.position;
      this.title = "景区信息更新";
      this.drawer = true;
    },
    cancelForm() {
      this.drawer = false;
      this.form = {};
      if (this.flag) this.flag = 0;
    },
    handleClose() {
      this.drawer = false;
      this.form = {};
      this.thisPosition={}
      if (this.flag) this.flag = 0;
    },

    // 图片上传成功返回图片地址
    handleAvatarSuccess(res, file) {
      // 如果上传成功
      if (res) {
        console.log(res);
        this.form.imglist.push(res.imagePath);
      } else {
        ElMessage({
          message: "提交失败！",
          type: "error",
        });
      }
    },
    deleteimg(index) {
      this.$confirm("是否删除该照片, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          this.form.imglist.splice(index, 1); // 从下标index开始，删除1个元素
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    async finish() {
      this.form.imglist = JSON.stringify(this.form.imglist);
      if (!this.flag) {
        this.form.position = JSON.stringify(this.thisPosition);
        let result = await updatehotdata(this.form);
        if (result.status == 0) {
          this.$message({
            message: "更新成功！",
            type: "success",
          });
          this.thisPosition = {};
          this.drawer = false;
          this.initdata();
        }
      } else {
        this.form.position = JSON.stringify(this.thisPosition);
        let result = await addehotdata(this.form);

        if (result.status == 0) {
          this.$message({
            message: "添加成功！",
            type: "success",
          });
          this.thisPosition = {};
          this.drawer = false;
          this.initdata();

          this.flag = 0;
        }
      }
    },
    add() {
      this.form = {};
      this.flag = 1;
      this.title = "景区信息添加";
      this.drawer = true;
      this.form.imglist = [];
    },
    mapdialogBeforeClose() {
      this.keyword='',
      this.poiList=[];
      this.mapdialogVisible = false;
    },
  },
};
</script>

<style scoped>
.container {
  margin-left: 50px;
}

.modify {
  margin-left: 10px;
}

#map-box {
  width: 100%;
  height: 450px;
  position: relative;
}

#mymap {
  width: 100%;
  height: 100%;
}

#myPageTop {
  position: absolute;
  top: 5px;
  right: 10px;
  font-family: "Microsoft Yahei", Pinghei;
  font-size: 14px;
  background: none 0px 0px repeat scroll rgb(255, 255, 255);
  border-width: 1px;
  border-style: solid;
  border-color: rgb(204, 204, 204);
  border-image: initial;
  margin: 10px auto;
  padding: 6px;
  display: flex;
}

#panel {
  background-color: white;
  max-height: 400px;
  overflow-y: auto;
}

.map_search_result {
  background-color: white;
  position: absolute;
  top: 53px;
  right: 10px;
  overflow-y: auto;
}

.item {
  padding: 10px;
  border-bottom: solid 1px #eee;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  display: inline-block;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
  display: inline-block;
}

.avatar {
  width: 178px;
  height: 178px;
  display: inline-block;
}
</style>